# coding:utf-8
from typing import Optional

from fastapi import APIRouter, Query, Path, Security
from tortoise.expressions import Q

from app.dependencies.verify import verify_token
from app.admin.schemas.system import AdminUpdate, AdminCreate
from app.core.response import SuccessExtra, Success, Fail
from app.admin.service.system.admin import AdminService

router = APIRouter()


# , response_model=Page[AdminOutDB]
@router.get("/user/list", summary="系统用户列表", dependencies=[Security(verify_token, scopes=["system:admin:list"])])
async def page_list(
        page: int = Query(1, description="页码"),
        limit: int = Query(10, description="每页数量"),
        username: str = Query(None, description="用户名称，用于搜索"),
        status: Optional[str] = Query(None, description="用户状态"),
):
    # 查询条件
    query = Q()
    if username:
        query &= Q(username__contains=username)
    if status and int(status) in [0, 1, 2]:
        query &= Q(status__lt=status)
    model_service = AdminService()
    total, lists = await model_service.page_list(query, page, limit)
    data = [await obj.to_dict(m2m=True, exclude_fields=["password", "is_delete"]) for obj in lists]
    return SuccessExtra(data=data, total=total, page=page, limit=limit)


@router.get("/user/{item_id}", summary="查看用户")
async def get_detail(item_id: int = Path(..., description="用户ID"), ):
    model_service = AdminService()
    item_obj = await model_service.get_id(item_id)
    if not item_obj:
        return Fail(msg="用户不存在")
    item_dict = await item_obj.to_dict(exclude_fields=["password"])
    return Success(data=item_dict)


@router.post("/user/create", summary="创建用户")
async def create(user_in: AdminCreate):
    model_service = AdminService()
    # 构建查询条件
    query = Q(username=user_in.username)
    item = await model_service.find(query)
    if item:
        return Fail(msg="用户已存在")
    new_item = await model_service.create(obj_in=user_in)
    if not new_item:
        return Fail(msg="用户创建失败")
    return Success(msg="操作成功")


@router.post("/user/update", summary="更新用户")
async def update(data_in: AdminUpdate):
    model_service = AdminService()
    user = await model_service.update(obj_in=data_in)
    return Success(msg="操作成功")


@router.delete("/user/delete/{item_id}", summary="删除用户")
async def delete(item_id: int = Path(..., description="用户ID")):
    model_service = AdminService()
    await model_service.remove(item_id)
    return Success(msg="操作成功")
